<template>
	<div>
		<!-- :action="ossUploadUrl" -->
		<!-- :http-request="Upload" -->
		<!-- 注意：必须关闭自动上传属性 auto-upload -->
		<el-upload :multiple="true" list-type="picture-card" :class="{ hide: hideUpload }" :file-list="productImageList" :on-remove="removeImage"
			:limit="maxCount" :before-upload="beforeUpload" ref="fileUpload" :auto-upload="false"
			:on-change="selectChange" :http-request="Upload" action='' :on-preview="handlePreview"
			:on-success="handleUploadSuccess" :on-exceed="handleExceed" class="cropper-upload-box">
			<i slot="default" class="el-icon-plus"></i>
		</el-upload>
		<el-dialog modal-append-to-body append-to-body :visible.sync="dialogVisible" width="740px" top="2vh"
			title="图片裁剪" :before-close="handleClose" :close-on-click-modal="false">
			<cropper v-if="showCropper" :dialog-visible="showCropper" :cropper-img="cropperImg" :zoomScale="zoomScale"
				@update-cropper="updateCropper" @colse-dialog="closeDialog" @upload-img="uploadImg" />
		</el-dialog>
		<el-dialog append-to-body :visible.sync="imgVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	import Cropper from "@/components/cropper";
	export default {
		name: "CropperUpload",
		data() {
			return {
				hideUpload:false,
				productImageList: [],
				dialogVisible: false,
				showCropper: false, // 是否显示裁剪框
				cropperImg: "", // 需要裁剪的图片
				ossUploadUrl: 'https:vue upload 首次不回显图片//yuelinguangchang.oss-cn-qingdao.aliyuncs.com',
				// ossUploadUrl: process.env.BASE_API +'/file/upload',
				dataObj: {
					policy: '',
					signature: '',
					key: '',
					ossaccessKeyId: '',
					dir: '',
					host: ''
				},
				uploadFile: null,
				imgVisible: false,
				dialogImageUrl: ''
			};
		},
		props: {
			value: { // 默认显示的图片列表
				type: Array,
				default: () => []
			},
			zoomScale: { // 裁剪比例，默认1:1
				type: Array,
				default: [1, 1]
			},
			fileSize: {
				type: Number,
				default: 5
			},
			maxCount: {
				type: Number,
				default: 9
			},
		},
		components: {
			Cropper
		},
		watch: {
			value: {
				handler: function(newVal, oldVal) {
					this.productImageList = []
					for (let i = 0; i < newVal.length; i++) {
						this.productImageList.push({
							url: this.value[i]
						});
					}
					this.hideUpload = this.productImageList.length >= this.maxCount;
				},
				deep: true
			}
		},
		mounted() {
			if (this.value && this.value.length != 0) {
				this.productImageList = []
				for (let i = 0; i < this.value.length; i++) {
					this.productImageList.push({
						url: this.value[i]
					});
				}
				this.hideUpload = this.productImageList.length >= this.maxCount;
			}
		},
		methods: {
			emitInput(fileList) {
				let value = [];
				for (let i = 0; i < fileList.length; i++) {
					value.push(fileList[i].url);
				}
				this.hideUpload = this.productImageList.length >= this.maxCount;
				this.$emit('input', value)
			},
			handlePreview(file) {
				this.imgVisible = true;
				this.dialogImageUrl = file.url;
			},
			handleUploadSuccess(res, file) {
				let url = this.dataObj.host + '/' + this.dataObj.key;
				this.productImageList.push({
					name: file.name,
					url: url
				});
				
				this.hideUpload = this.productImageList.length >= this.maxCount;
				this.$emit('input', this.productImageList);

			},
			handleExceed(files, fileList) {
				this.$message({
					message: '最多只能上传' + this.maxCount + '张图片',
					type: 'warning',
					duration: 1000
				});
			},
			// 取消关闭弹框
			handleClose() {
				this.dialogVisible = false
			},
			async beforeUpload(file) {
				// let types = ['image/jpeg', 'image/jpg', 'image/png'];
				// const isImage = types.includes(file.type);
				// if (!isImage) {
				// 	this.$message.error('上传图片只支持JPG、JPEG、PNG格式!')
				// 	return false
				// }
				// const isLt5M = file.size / 1024 / 1024 < this.fileSize
				// if (!isLt5M) {
				// 	this.$message.error('上传图片不能超过' + this.fileSize + 'M')
				// 	return false
				// }
				// return true
				let _self = this;
				let filename = new Date().getTime() + '_' + file.name.replace(',', '')
				return new Promise((resolve, reject) => {
					this.$get('/file/upToken').then(response => {
						_self.dataObj.policy = response.data.policy;
						_self.dataObj.signature = response.data.signature;
						_self.dataObj.ossaccessKeyId = response.data.accessKeyId;
						_self.dataObj.key = response.data.dir.substring(0) + '/' + filename;
						_self.dataObj.dir = response.data.dir;
						_self.dataObj.host = response.data.host;
						resolve(true)
					}).catch(err => {
						console.log(err)
						reject(false)
					})
				})
			},
			removeImage(file, fileList) {
				this.productImageList = fileList
				this.hideUpload = this.productImageList.length >= this.maxCount;
				this.$emit('input', fileList)
			},
			async Upload(param) {
				let file = param.file;
				let formData = new FormData();
				formData.append("policy", this.dataObj.policy);
				formData.append("signature", this.dataObj.signature);
				formData.append("ossaccessKeyId", this.dataObj.ossaccessKeyId);
				formData.append("key", this.dataObj.key);
				formData.append("dir", this.dataObj.dir);
				formData.append("host", this.dataObj.host);
				formData.append("file", this.uploadFile);
				let params = {
					...this.dataObj,
					file: this.uploadFile
				}
				// const res = await this.$uploadFile('/file/upload', params)
				const res = await this.$axios({
					method: 'post',
					url: 'https://yuelinguangchang.oss-cn-qingdao.aliyuncs.com',
					data: formData,
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				})
				console.log(res, "res")
				// this.productImageList.push({
				// 	url: res.data,
				// 	uid: param.uid
				// });
				this.showCropper = false;
				this.dialogVisible = false
				this.$emit('input', this.productImageList) // 把最新上传的图片列表返回
			},

			// 更新图片
			updateCropper() {
				if (!this.noCanUpload) {
					let fileList = this.$refs.fileUpload.uploadFiles // 获取文件列表
					let index02 = fileList.findIndex(item => { // 把取消裁剪的图片删除
						return item.uid == this.currentFile.uid;
					});
					fileList.splice(index02, 1)
				}

				let index = this.$refs.fileUpload.$children.length - 1;
				this.$refs.fileUpload.$children[index].$el.click();
			},
			// 关闭窗口
			closeDialog() {
				this.dialogVisible = false
				this.showCropper = false;

				if (!this.noCanUpload) {
					let fileList = this.$refs.fileUpload.uploadFiles // 获取文件列表
					let index = fileList.findIndex(item => { // 把取消裁剪的图片删除
						return item.uid == this.currentFile.uid;
					});
					fileList.splice(index, 1)
				}
			},
			// 上传图片
			uploadImg(file) {
				this.uploadFile = file;
				// this.$refs.fileUpload.submit();

				// 判断裁剪后图片的宽高
				let img = new Image()
				img.src = window.URL.createObjectURL(file); // Blob转成url 才能给img显示
				img.onload = () => {
					let minProp = Math.min(img.width, img.height) //裁剪后的图片宽，高  ==> 取最小值
					// if (minProp < 500) { // 如果最小值比设置的最小值（默认为500）小
					// 	this.$message.error(`请保证图片短边最小为500`);
					// 	return false
					// }
					this.$refs.fileUpload.submit();
				}
			},
			selectChange(file, fileList) {
				if (file.status == 'success') return
				this.noCanUpload = false
				let files = file.raw;
				var reader = new FileReader();
				reader.onload = e => {
					let data;
					if (typeof e.target.result === "object") {
						// 把Array Buffer转化为blob 如果是base64不需要
						data = window.URL.createObjectURL(new Blob([e.target.result]));
					} else {
						data = e.target.result;
					}
					this.cropperImg = data;

					// 图片图片尺寸，如果是正方形，则直接上传；否则调用裁剪
					let img = new Image()
					img.src = this.cropperImg;
					img.onload = () => {
						// if (img.width == img.height) { // 本来就是正方形 => 直接上传
						// 	this.uploadFile = files;
						// 	this.$refs.fileUpload.submit(); // 调用上传方法
						// } else {
						// 	this.showCropper = true; // 不是正方形的图片才开启裁剪
						// 	this.currentFile = file // 保存当前操作裁剪的图片
						// }
						this.showCropper = true; // 不是正方形的图片才开启裁剪
						this.dialogVisible = true
						this.currentFile = file // 保存当前操作裁剪的图片
					}
				};
				// 转化为base64
				// reader.readAsDataURL(file)
				// 转化为blob
				reader.readAsArrayBuffer(files);

				this.showCropper = true; // 默认开启裁剪
			}
		}
	};
</script>

<style lang="scss">
	.cropper-upload-box {
		display: flex;

		.el-upload {
			width: 148px;
			height: 148px;
		}
	}
	.hide .el-upload--picture-card {
	display: none;
}
</style>
